//
//  UIImageView+TP_Utility.m
//  E_Car
//  添加点击事件block
//  Created by 谭鹏 on 2017/4/15.
//  Copyright © 2017年 谭鹏. All rights reserved.
//

#import "UIImageView+TP_Utility.h"
#import <objc/runtime.h>
#import <ImageIO/ImageIO.h>

static NSString * tapActionBlockKey = @"tapActionBlockKey";
@implementation UIImageView (TP_Utility)


-(instancetype)initWithGifName:(NSString *)gifName animationDuration:(NSTimeInterval)animationDuration{
    self = [super init];
    if (self) {
        NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:gifName withExtension:@"gif"]; //加载GIF图片
        CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef) fileUrl, NULL);           //将GIF图片转换成对应的图片源
        size_t frameCout = CGImageSourceGetCount(gifSource);                                         //获取其中图片源个数，即由多少帧图片组成
        NSMutableArray *frames = [[NSMutableArray alloc] init];                                      //定义数组存储拆分出来的图片
        for (size_t i = 0; i < frameCout; i++) {
            CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, NULL); //从GIF图片中取出源图片
//            UIImage *imageName = [UIImage imageWithCGImage:imageRef];                  //将图片源转换成UIimageView能使用的图片源
            UIImage *imageName = [UIImage imageWithCGImage:imageRef scale:2 orientation:UIImageOrientationUp];
//            NSLog(@"scale %f", imageName.scale);
            
            [frames addObject:imageName];                                              //将图片加入数组中
            CGImageRelease(imageRef);
        }
        
        self.animationImages = frames; //将图片数组加入UIImageView动画数组中
        self.animationDuration = animationDuration; //每次动画时长
//        [self startAnimating];         //开启动画，此处没有调用播放次数接口，UIImageView默认播放次数为无限次，故这里不做处理
        
    }
    return self;
}


#pragma mark - set&get
//runtime 设置block属性
@dynamic tapActionBlock;
-(void)setTapActionBlock:(TapActionBlock)tapActionBlock{
    self.userInteractionEnabled = YES;
    UITapGestureRecognizer * tapGR = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapSelf)];
    [self addGestureRecognizer:tapGR];
    
    objc_setAssociatedObject(self, &tapActionBlockKey, tapActionBlock, OBJC_ASSOCIATION_COPY);
}

-(TapActionBlock)tapActionBlock{
    return objc_getAssociatedObject(self, &tapActionBlockKey);
}

//+(void)load{
//    [super load];
//    class_setSuperclass(NSClassFromString(@"UIView"), NSStringFromClass(@"TPView"));
//    
//}
#pragma mark - action
-(void)tapSelf{
    if (self.tapActionBlock) {
        self.tapActionBlock();
    }
    
}
@end
